import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:yt_devops/components/paging/page_state.dart';
import 'package:yt_devops/model/device_model.dart';
import 'package:yt_devops/model/device_product_type_model.dart';
import 'package:yt_devops/model/info_item.dart';
import 'package:yt_devops/pages/devices/device_list/components/filter_product_tags.dart';
import 'package:yt_devops/pages/devices/device_list/components/filter_site_tags.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';

class DeviceListState extends PagingState<DeviceListModel> {
  ConnectStatusType? connectStatus;
  String? name;
  String? sn;
  String? snOrName;
  DeviceAlarmStatus? alarmStatus;
  int? productTypeId; //产品类型
  String? productTypeIds; // 产品id集合
  String? deviceName; //产品名称
  int? subSystemId; //单元id
  ProductTypeEnity? productTypeEnity;
  //已选中的站点列表
  List<SiteTagModel> selectedSites = [];

  int? get siteId =>
      FuncUtils.isEmpty(selectedSites) ? null : selectedSites.first.siteId;

  //站点id集合
  String get siteIds =>
      selectedSites.map<int>((site) => site.siteId!).toList().join(",");

  void init() {
    selectedSites = [];
    productTypeId = null;
    productTypeIds = null;
    deviceName = null;
    subSystemId = null;
    productTypeEnity = null;
  }
}

class DeviceListModel {
  int? deviceId;
  int? productId;
  String? siteName;
  int? siteId;
  int? canBeDeleted;
  int? canUnbind; //该设备能否解绑（0不能解绑 1能解绑)
  String? sn;
  String? name;
  String? deviceName;
  ConnectStatusType? connectStatus;
  String? createTime;
  int? productType;
  List<DeviceListModel>? childDeviceList;
  DeviceAlarmStatus? alarmStatus;
  String? productTypeName;
  String? subsystemName;
  String? model;
  String? groupName;
  MasterSlaveModeType? masterSlaveMode;

  DeviceListModel(
      {this.deviceId,
      this.productId,
      this.siteId,
      this.canBeDeleted,
      this.canUnbind,
      this.sn,
      this.name,
      this.deviceName,
      this.connectStatus,
      this.siteName,
      this.groupName,
      this.createTime,
      this.childDeviceList,
      this.alarmStatus,
      this.productTypeName,
      this.subsystemName,
      this.model,
      this.masterSlaveMode,
      this.productType});

  factory DeviceListModel.fromJson(Map<String, dynamic> jsons) =>
      DeviceListModel(
        deviceId: jsons['deviceId'],
        productId: jsons['productId'],
        siteId: jsons['siteId'],
        canBeDeleted: jsons['canBeDeleted'],
        canUnbind: jsons['canUnbind'],
        sn: jsons['sn'],
        name: jsons['name'],
        deviceName: jsons['deviceName'],
        groupName: jsons['groupName'],
        connectStatus: $enumDecodeNullable(
            $ConnectStatusTypeEnumMap, jsons['connectStatus']),
        createTime: jsons['createTime'],
        productType: jsons['productType'],
        childDeviceList: (jsons['childDeviceList'] as List?)
            ?.map((e) => DeviceListModel.fromJson(e as Map<String, dynamic>))
            ?.toList(),
        productTypeName: jsons['productTypeName'],
        subsystemName: jsons['subsystemName'],
        model: jsons['model'],
        siteName: jsons['siteName'],
        alarmStatus: $enumDecodeNullable(
            $DeviceAlarmStatusTypeEnumMap, jsons['alarmStatus']),
        masterSlaveMode: $enumDecodeNullable(
            $MasterSlaveModeEnumMap, jsons['masterSlaveMode']),
      );

  List<InfoItem> get infos => [
        if (siteId != null) InfoItem(ResKey.siteName.tr, siteName ?? ''),
        InfoItem(ResKey.deviceSn.tr, sn ?? ''),
        InfoItem(
          ResKey.alarmStatus.tr,
          alarmStatus?.label ?? '',
          valueTextStyle: alarmStatus == DeviceAlarmStatus.normal
              ? TextStyles.f14.copyWith(color: Colour.green)
              : TextStyles.f14.copyWith(color: Colour.warningTextColor),
        ),
        InfoItem(ResKey.productType.tr, productTypeName ?? ''),
        InfoItem(ResKey.productModel.tr, model?.toString() ?? ''),
      ];
}

/// 产品详情
class ProductDetailModel {
  /// brokerid字段
  int? brokerId;

  /// homeDisplay是否在示范站首页设备列表展示 0:不展示 1:展示; selectDisplay用于添加设备的时候，0-不显示 1显示;
  /// initSubDevice用于添加设备时所要初始化的子设备列表name为设备名，productId为型号id; deviceTreeDisplay用于设备树是否显示：0-不显示
  /// 1显示，默认显示; pvNum光伏逆变器组串数量 functionType空调功能 标识是否有下发功能 0否1是
  Config? config;

  /// 描述信息
  String? description;

  /// 是否在示范站首页设备列表展示 0:不展示 1:展示
  int? display;

  /// 供应商ID
  int? factoryId;

  /// 是否有网络状态0没有 1有
  int? hasStatus;
  int? id;

  /// 产品型号
  String? model;
  String? name;

  /// 1直连 2网关子设备 3网关设备
  int? nodeType;

  /// 产品类型
  int? productType;
  String? protocolCode;

  /// 物模型ID
  int? thingsMode;

  ProductDetailModel({
    this.brokerId,
    this.config,
    this.description,
    this.display,
    this.factoryId,
    this.hasStatus,
    this.id,
    this.model,
    this.name,
    this.nodeType,
    this.productType,
    this.protocolCode,
    this.thingsMode,
  });

  factory ProductDetailModel.fromMap(Map<String, dynamic> json) =>
      ProductDetailModel(
        brokerId: json["brokerId"],
        config: Config.fromMap(json["config"]),
        description: json["description"],
        display: json["display"],
        factoryId: json["factoryId"],
        hasStatus: json["hasStatus"],
        id: json["id"],
        model: json["model"],
        name: json["name"],
        nodeType: json["nodeType"],
        productType: json["productType"],
        protocolCode: json["protocolCode"],
        thingsMode: json["thingsMode"],
      );

  Map<String, dynamic> toMap() => {
        "brokerId": brokerId,
        "config": config!.toMap(),
        "description": description,
        "display": display,
        "factoryId": factoryId,
        "hasStatus": hasStatus,
        "id": id,
        "model": model,
        "name": name,
        "nodeType": nodeType,
        "productType": productType,
        "protocolCode": protocolCode,
        "thingsMode": thingsMode,
      };
}

///homeDisplay是否在示范站首页设备列表展示 0:不展示 1:展示; selectDisplay用于添加设备的时候，0-不显示 1显示;
///initSubDevice用于添加设备时所要初始化的子设备列表name为设备名，productId为型号id; deviceTreeDisplay用于设备树是否显示：0-不显示
///1显示，默认显示; pvNum光伏逆变器组串数量 functionType标识那个ems或者空调   0矩形 1比瓦特 2自研，homeDisplay是否在示范站首页设备列表展示
///0:不展示 1:展示; selectDisplay用于添加设备的时候，0-不显示 1显示;
///initSubDevice用于添加设备时所要初始化的子设备列表name为设备名，productId为型号id; deviceTreeDisplay用于设备树是否显示：0-不显示
///1显示，默认显示; pvNum光伏逆变器组串数量 functionType标识那个ems或者空调   0矩形 1比瓦特 2自研
class Config {
  int? functionType;
  int? selectDisplay;

  Config({
    this.functionType,
    this.selectDisplay,
  });

  factory Config.fromMap(Map<String, dynamic> json) => Config(
        functionType: json["functionType"],
        selectDisplay: json["selectDisplay"],
      );

  Map<String, dynamic> toMap() => {
        "functionType": functionType,
        "selectDisplay": selectDisplay,
      };
}
